<template>
  <div class="form-item-label" :style="labelWidthStyle">
    <a-tooltip v-if="searchItem.tooltipContent" :content="searchItem.tooltipContent">
      <icon-question-circle class="mr-1" style="min-width: 15%" />
    </a-tooltip>
    <a-select
      :class="['form-item-label-select', { searchGroup: searchItem.tooltipContent }]"
      :allow-clear="false"
      v-model:model-value="_searchItem.prop"
      @change="propChange"
    >
      <a-option v-for="item in searchItem.childrens" :key="item.prop" :value="item.prop">
        {{ item.label }}
      </a-option>
    </a-select>
  </div>
  <div class="form-item-content" :style="contentWidthStyle">
    <portal
      v-model="activedVal"
      v-bind="activedItem"
      @press-enter="portalPressEnterChangeFn"
      @clear="portalClearFn"
      @change="portalChangeFn"
    />
  </div>
</template>

<script setup>
  import { ref, onMounted, computed } from 'vue'
  import portal from './portal.vue'
  const props = defineProps({
    searchItem: Object,
    modelValue: undefined,
    labelWidthStyle: Object,
    contentWidthStyle: Object,
  })

  const _searchItem = computed(() => {
    return props.searchItem
  })

  const emit = defineEmits(['update:modelValue', 'group-change', 'press-enter', 'change'])
  const activedVal = computed({
    set(val) {
      emit('update:modelValue', val)
    },
    get() {
      return props.modelValue
    },
  })

  // 初始 portal 初始值
  onMounted(() => {
    propChange(_searchItem.value.prop)
  })

  const activedItem = ref({})
  const propChange = (val) => {
    let oldVal = activedItem.value.prop
    if (oldVal) emit('group-change', val, oldVal)
    // 获取最新的 activeItem
    activedItem.value = _searchItem.value.childrens.find((item) => item.prop == val)
  }

  // 子组件press-enter传递函数
  const portalPressEnterChangeFn = (...args) => {
    emit('press-enter', activedItem.value, ...args)
  }
  // 子组件change传递函数
  const portalChangeFn = (...args) => {
    emit('change', activedItem.value, ...args)
  }
  // 子组件clear
  const portalClearFn = () => {
    emit('update:modelValue', undefined)
  }
</script>

<style lang="less" scoped>
  .form-item-label {
    display: flex;
    padding: 0 6px;
    align-items: flex-start;
  }
  :deep {
    .form-item-label-select {
      border: 1px #ccc solid !important;
      background: none !important;
    }
    // 针对下拉框左侧带有问号的样式,参考页面：短租对账-取还车日期（后期需整改）
    .searchGroup {
      max-width: 80%;
      padding: 0 6px !important;
      .arco-select-view-suffix {
        padding-left: 4px !important;
      }
    }
  }
</style>
